﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EchoPlanNote.Common;
using EchoPlanNote.IServices;
using EchoPlanNote.Model;
using EchoPlanNote.Services;

namespace EchoPlanNote.Web.Controllers
{
    public class AccountController : Controller
    {
        private IUsersService userinfoSer;

        public AccountController(IUsersService sercice)
        {
            userinfoSer = sercice;
        }

        // GET: Account
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login(string returnUrl)
        {
            ViewBag.UserName = Request.Cookies["n"]?.Value;
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        public ActionResult Login(Users user, string returnUrl)
        {
            if (!string.IsNullOrWhiteSpace(user.UserName) || !string.IsNullOrWhiteSpace(user.PassWord))
            {
                var userInfo = userinfoSer.QueryWhere(u => u.UserName.Equals(user.UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                if (userInfo != null)
                {
                    if (userInfo.PassWord.Equals(user.PassWord.GetMD5(), StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (string.IsNullOrWhiteSpace(returnUrl))
                        {
                            returnUrl = "/Home/Index";
                        }
                        Session["UserInfo"] = user;
                        HttpCookie c1 = new HttpCookie("n", userInfo.UserName);
                        HttpCookie c2 = new HttpCookie("p", userInfo.PassWord);
                        c1.Expires = c2.Expires = DateTime.Now.AddDays(3);
                        Response.Cookies.Add(c1);
                        Response.Cookies.Add(c2);
                        return Json(new { code = "200", msg = returnUrl });
                    }
                    else
                    {
                        return Json(new { code = "400", msg = "用户名或密码错误" });
                    }
                }
                else
                {
                    return Json(new { code = "400", msg = "用户不存在" });
                }
            }
            else
            {
                return Json(new { code = "400", msg = "用户名或密码不能为空" });
            }
        }
        
        public ActionResult Logout()
        {
            return Json(new { code = "200" }, JsonRequestBehavior.AllowGet);
        }
    }
}